package com.gin.no_gay_alliance.adpter;

import android.view.ViewGroup;
import android.widget.Switch;

import androidx.annotation.IntRange;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.gin.no_gay_alliance.param.SearchArea;

import java.util.ArrayList;
import java.util.List;

/**
 * 搜索区域适配器
 *
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/8/9 16:35
 **/
public class SearchAreaAdapter extends RecyclerView.Adapter<SearchAreaAdapter.ViewHolder> {
    private List<SearchArea> data;

    public SearchAreaAdapter() {
        this(new ArrayList<>());
    }


    public SearchAreaAdapter(List<SearchArea> data) {
        this.data = data;
    }

    public void insertData(SearchArea item, @IntRange(from = 0) int index) {
        data.add(index, item);
        notifyItemInserted(index);
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // 加载布局文件  填写需要渲染的布局文件
        return new ViewHolder(new Switch(parent.getContext()));
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        // 填充数据到各个子view
        SearchArea area = data.get(position);
        holder.sw.setText(area.name);
        holder.sw.setChecked(area.checked);
        holder.sw.setOnCheckedChangeListener((v, c) -> {
            area.checked = c;
        });
    }

    @Override
    public int getItemCount() {
        return data == null ? 0 : data.size();
    }

    public void setData(List<SearchArea> data) {
        this.data = data;
        notifyDataSetChanged();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        Switch sw;

        public ViewHolder(@NonNull Switch itemView) {
            super(itemView);
            sw = itemView;
        }
    }
}